package com.wing.wecom.service;

import chat.qiye.wechat.sdk.api.contact.ContactUserApi;
import chat.qiye.wechat.sdk.api.contact.param.ContactUserBatchDeleteParam;
import chat.qiye.wechat.sdk.api.contact.param.ContactUserParam;
import chat.qiye.wechat.sdk.api.contact.resp.ContactUserGetResp;
import chat.qiye.wechat.sdk.common.RespStatus;
import chat.qiye.wechat.sdk.constant.AppTypeEnum;
import chat.qiye.wechat.sdk.service.ApiConfigurationDefaultProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 企业微信用户-ContactUserServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class ContactUserServiceImpl implements ContactUserService {

    @Resource
    ContactUserApi contactUserApi;
    @Resource
    ApiConfigurationDefaultProvider apiConfigurationDefaultProvider;

    @Override
    public RespStatus create(ContactUserParam contactUserParam) {
        RespStatus respStatus = contactUserApi.create(contactUserParam);
        if(respStatus.getErrcode() == 42001){ // access_token已过期
            apiConfigurationDefaultProvider.loadAppToken(AppTypeEnum.APP_CONTACT.getAppId());
            respStatus = contactUserApi.create(contactUserParam);
        }
        return respStatus;
    }

    @Override
    public int get(String userid) {
        ContactUserGetResp contactUserGetResp = contactUserApi.get(userid);
        return contactUserGetResp.success() ? 1 : 0;
    }

    @Override
    public RespStatus update(ContactUserParam contactUserParam) {
        RespStatus respStatus = contactUserApi.update(contactUserParam);
        if(respStatus.getErrcode() == 42001){ // access_token已过期
            apiConfigurationDefaultProvider.loadAppToken(AppTypeEnum.APP_CONTACT.getAppId());
            respStatus = contactUserApi.update(contactUserParam);
        }
        return respStatus;
    }

    @Override
    public RespStatus delete(String userid) {
        RespStatus respStatus = contactUserApi.delete(userid);
        if(respStatus.getErrcode() == 42001){ // access_token已过期
            apiConfigurationDefaultProvider.loadAppToken(AppTypeEnum.APP_CONTACT.getAppId());
            respStatus = contactUserApi.delete(userid);
        }
        return respStatus;
    }

    @Override
    public int deleteBatch(ContactUserBatchDeleteParam contactUserBatchDeleteParam) {
        RespStatus respStatus = contactUserApi.deleteBatch(contactUserBatchDeleteParam);
        return respStatus.success() ? 1 : 0;
    }

}
